package net.lainiao.morethread.Chapter5.demo3;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * Created by Administrator on 2017/3/6.
 */
public class FolderProcessor extends RecursiveTask<List<String>> {
    private static final long serialVersionUID = 1L;
    private String path;
    private String extension;

    public FolderProcessor(String path, String extension) {
        this.path = path;
        this.extension = extension;
    }

    @Override
    protected List<String> compute() {
        List<String> list=new ArrayList<>();
        List<FolderProcessor> tasks=new ArrayList<>();
        File file=new File(path);
        File[] content=file.listFiles();
        if(content!=null){
            for (int i = 0; i < content.length; i++) {
                File temFile=content[i];
                if(temFile.isDirectory()){
                    FolderProcessor task=new FolderProcessor(content[i].getAbsolutePath(),extension);
                    task.fork();
                    tasks.add(task);
                }else{
                    if(checkFile(temFile.getName())){
                        list.add(temFile.getAbsolutePath());
                    }
                }
            }
            if(tasks.size()>50){
                System.out.println(file.getAbsoluteFile()+" task ran "+tasks.size());
            }
            addresultFromTask(list,tasks);
        }
        return list;
    }

    private boolean checkFile(String name) {
        return name.endsWith(extension);
    }

    private void addresultFromTask(List<String> list, List<FolderProcessor> tasks) {
        for (FolderProcessor folderProcessor :tasks){
            list.addAll(folderProcessor.join());
        }
    }
}
